<?php
/**
 * Created by PhpStorm.
 * Author: huangwy
 * Date: 2018/3/16 10:41
 * Version: 1.0
 */

namespace app\admin\model;

use think\Db;
use think\Model;

class Menu extends Model
{
    protected $tableName = 'auth_rule';
    /**
     * 删除菜单
     * @param string $ids
     */
    public function menu_del($ids=''){
        $ids = isset($ids) ? $ids : false;
        if (!$ids) {
            return 999;
        }

        //判断该栏目是否有子栏目
        $son_ids=$this->getChildsId(db('auth_rule')->order('o asc')->select(),$ids);
        if(!empty($son_ids)){//有子栏目，不允许删除
            return 998;
        }
        if (db('auth_rule')->delete($ids)) {

            addlog('删除菜单ID：' . $ids);
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @param string $info
     */
    public function menu_update($info=''){
        $id = $info['id'];
        $data['pid'] = $info['pid'];
        $data['title'] = $info['title'];
        $data['name'] = $info['name'];
        $data['icon'] = 'menu-icon '.$info['icon'];
        $data['islink'] = !empty($info['islink']) ? $info['islink'] : 0;
        $data['status'] = 1;
        $data['o'] = $info['o'];
        $data['tips'] = $info['tips'];
        if ($id) {
            db('auth_rule')->data($data)->where("id=".$id)->update();
            addlog('编辑菜单，ID：' . $id);
        } else {
            db('auth_rule')->data($data)->insert();
            addlog('新增菜单，名称：' . $data['title']);
        }

        return true;
    }

    public function menu(){
        $option = db('auth_rule')->order('o ASC')->select();
        $option = getMenu($option);
        return $option;
    }


    /**
     * 传递一个父级分类ID返回所有子分类ID
     * @param unknown $cate
     * @param unknown $pid
     */
    public function getChildsId ($cate, $pid) {
        $arr = array();
        foreach ($cate as $v) {
            if ($v['pid'] == $pid) {
                $arr[] = $v['id'];
                $arr = array_merge($arr, $this->getChildsId($cate, $v['id']));
            }
        }
        return $arr;
    }
}